package cn.edu.jcu.kyle.gintama.OurUtil;

import cn.edu.jcu.kyle.gintama.DbUtil;
import cn.edu.jcu.kyle.gintama.Main;
import cn.edu.jcu.kyle.gintama.data.Phone.PhoneData;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.stage.Stage;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Objects;

public class PhoneQuery {
    private static final String url = "https://qqlykm.cn/api/free/phone/get?key=dc1itChVvwTSVzu6Ihh0E0PIwM&phone=";
    private static String phoneNum;        //电话号码
    private static String province;        //省份
    private static String city;            //城市
    private static String area_code;       //地区编码
    private static String post_code;       //邮政编码
    private static String isp;             //运营商
    private static Connection conn = null;
    private static ResultSet resultSet = null;

    public static void Query(String _phoneNum) {
        createTable();                                               //建立初始表
        phoneNum = _phoneNum;
        if (Objects.equals(_phoneNum, "")) {                      //输入电话号码为空
            Alert alert = new Alert(Alert.AlertType.WARNING);        //弹出警告窗口
            alert.setTitle("警告窗口");
            alert.setHeaderText("输入为空！");
            alert.showAndWait();
            return;
        }
        if (queryInSQL(_phoneNum)) {
            showInDb(_phoneNum);
        } else {
            String str = HttpUtil.get(url + _phoneNum);
            //发起http请求
            PhoneData data = JSONUtil.toBean(str, PhoneData.class);
            //把返回的json转成javaBean
            if (!data.getSuccess()) {                       //如果返回的json里显示请求失败
                Alert alert = new Alert(Alert.AlertType.WARNING);
                alert.setTitle("违法操作");
                alert.setHeaderText("获取失败！");
                alert.setContentText("请检查是否是接口调用次数达到限制或网络连接是否畅通\n或者是你单纯打错了电话号码");
                alert.showAndWait();
                return;
            } else if (data.getData().getArea_code() == null) {//如果返回的json里数据为null，说明输入有误
                Alert alert = new Alert(Alert.AlertType.WARNING);
                alert.setTitle("违法操作！");
                alert.setHeaderText("未找到电话号码！");
                alert.setContentText("输入错误！");
                alert.showAndWait();
                return;
            }
            writeIn(data);
            show();
            wINdb();
        }
    }

    private static boolean queryInSQL(String _phoneNum) {//查询搜索数据是否在数据库里存在
        try {
            conn = DbUtil.getMySQLConnection("jdbc:mysql://localhost:3306/gintama?useUnicode=utf8&useSSL=false");
            String str = "select * from Phone_Data where phoneNum='" + _phoneNum + "'";
            resultSet = DbUtil.executeQuery(conn, str);
            return resultSet.next();
        } catch (Exception e) {
            System.out.println("报错！");
            e.printStackTrace();
            return false;
        }
    }

    private static void writeIn(PhoneData data) {//构造函数
        province = data.getData().getProvince();
        city = data.getData().getCity();
        area_code = data.getData().getArea_code();
        post_code = data.getData().getPost_code();
        isp = data.getData().getIsp();
    }

    private static void show() {//展示当前搜索数据
        ListView<String> listView = new ListView<>();   //创建一个列表控件
        ObservableList<String> dataList = FXCollections.observableArrayList(
                "电话号码：" + phoneNum,
                "所在省份：" + province,
                "所在城市：" + city,
                "地区编码：" + area_code,
                "邮政编码：" + post_code,
                "运营商：" + isp);       //列表显示数据
        listView.setItems(dataList);
        Stage stage = new Stage();              //创建一个新窗口
        stage.setTitle("电话号码" + phoneNum); //新窗口的标题
        stage.getIcons().add(new Image(Objects.requireNonNull(Main.class.getResource("img/phone.png")).toExternalForm()));  //新窗口图标
        stage.setHeight(250);                   //新窗口高度
        stage.setWidth(300);                    //新窗口宽度
        stage.setScene(new Scene(listView));    //这个窗口里边装着上边那个列表控件
        stage.show();                           //弹出新窗口
    }

    private static void showInDb(String _phoneNum) {//展示数据库里的数据
        ListView<String> listViewDb = new ListView<>();   //创建一个列表控件
        ObservableList<String> dataList = null;
        try {
            dataList = FXCollections.observableArrayList(
                    "电话号码：" + resultSet.getString("PhoneNum"),
                    "所在省份：" + resultSet.getString("Province"),
                    "所在城市：" + resultSet.getString("City"),
                    "地区编码：" + resultSet.getString("Area_code"),
                    "邮政编码：" + resultSet.getString("Post_code"),
                    "运营商：" + resultSet.getString("Isp"));
        } catch (Exception e) {
            e.printStackTrace();
            AlertWindow.getWindow("警告！发生错误！");
            System.exit(-1);
        }
        listViewDb.setItems(dataList);
        Stage stageDb = new Stage();
        stageDb.setTitle("数据库中电话号码" + _phoneNum);
        stageDb.getIcons().add(new Image(Objects.requireNonNull(Main.class.getResource("img/phone.png")).toExternalForm()));  //新窗口图标
        stageDb.setHeight(250);
        stageDb.setWidth(300);
        stageDb.setScene(new Scene(listViewDb));
        stageDb.show();
    }

    private static void wINdb() {//写入数据库
        try {
            conn = DbUtil.getMySQLConnection("jdbc:mysql://localhost:3306/gintama?useUnicode=utf8&useSSL=false");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String insertSQL = "insert into Phone_Data (PhoneNum, Province, City, Area_code, Post_code, Isp) values (?, ?, ?, ?, ?, ?)";
        Object[] paramsInsert = {phoneNum, province, city, area_code, post_code, isp};
        DbUtil.executeUpdate(conn, insertSQL, paramsInsert);
    }

    private static void createTable() {//建个表
        String createTable = """
                create table if not exists gintama.Phone_Data
                (
                    PhoneNum   varchar(60) not null comment '电话号码',
                    Province   varchar(60) not null comment '所在省份',
                    City       varchar(60) not null comment '所在城市',
                    Area_code  varchar(60) not null comment '地区编码',
                    Post_code  varchar(60) not null comment '邮政编码',
                    Isp        varchar(60) not null comment '运营商',
                    constraint Phone_Data_pk
                        primary key (PhoneNum)
                )""";
        try {
            conn = DbUtil.getMySQLConnection("jdbc:mysql://localhost:3306/gintama?useUnicode=utf8&useSSL=false");
            DbUtil.executeUpdate(conn, createTable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
